#include "myclientsocket.h"
#include <QHostAddress>

myClientSocket::myClientSocket(databaseClass *db,QObject *parent,int my_ID) :
        QTcpSocket(parent)
{    
    //th = new QThread(this);
    //th->start();
    this->clientID=my_ID;
    connect(this,SIGNAL(readyRead()),this,SLOT(ReadData()));//挂接读取数据信号
    connect(this,SIGNAL(disconnected()),this,SLOT(DisConnect()));//关闭连接时，发送断开连接信号
    connect(this,SIGNAL(disconnected()),this,SLOT(deleteLater()));//关闭连接时，对象自动删除
    //this->moveToThread(th);
    this->myclassdb=db;

    my_dev_flag=QString::number(0);//设备类型
    MyPersonInfo = new conInfo();//下载卡号信息

    //下载卡定时器
    Download_timer =new QTimer(this);
    connect(Download_timer,SIGNAL(timeout()),this,SLOT(Download_netdata()));
    //删除卡定时器
    Delete_timer =new QTimer(this);
    connect(Delete_timer,SIGNAL(timeout()),this,SLOT(Delete_netdata()));
    //下载语音定时器
    Voice_timer =new QTimer(this);
    connect(Voice_timer,SIGNAL(timeout()),this,SLOT(Voice_netdata()));
    //数据接受
    Send_timer=new QTimer(this);
    connect(Send_timer,SIGNAL(timeout()),this,SLOT(Send_netdata()));
    //下载卡号
    myClient_card_no.clear();
    myDelet_card_no.clear();

    down_falg=true;//下载标志(设备类型为2使用)
    TIMER_falg=false;//心跳包标志
    OpenDoorData.clear();
    //  Client_flag=true;
    OpenTime=QDateTime::currentDateTime().addSecs(-4);
    del_num=0;
    dow_num=0;
}

myClientSocket::~myClientSocket()
{
    this->close();
    Download_timer->stop();
    Delete_timer->stop();
}

void myClientSocket::ReadData()
{
    //读取完整一条数据并发送信号
    QByteArray data=this->readAll();
    //qDebug()<<"socket Rec:" << data;
    emit ClientReadData(this->clientID,this->peerAddress().toString(),this->peerPort(),data);
    QStringList list;
    QString sendata,strSend,IP;
    strSend=QString(data);
    if(strSend.indexOf(",") < 0 || !this->myclassdb->mySql_db.isOpen())
    {
        //qDebug()<<"数据串校验:"<<strSend.indexOf(",")<<" 数据库连接状态:"<<this->myclassdb->mySql_db.isOpen();
        return;
    }
    list=strSend.split(',');
    IP=this->peerAddress().toString();
    if(list.count() > 3)
    {
        QString dev_Id,dev_flag,dev_byte,dev_number;
        bool res;
        dev_Id=list[0];//设备号
        dev_number=list[1];//设备类型号
        dev_flag=list[2];//标志
        dev_byte=list[3];
        //TCP连接信息
        tcpInfo Info;
        Info.tcp_id=clientID;//进程号
        Info.tcp_ip=IP;//设备IP
        Info.tcp_port=this->peerPort();//设备Port
        //TCP连接检测
        //tcpSocketConnect(dev_Id,IP,Info);

        if(dev_number== "1")//奶柜接口
        {
            if(dev_flag=="TIMER")//客户端发送心跳包(代温度)
            {
                sendata=dev_Id;
                res=this->myclassdb->controller_sn_infor(sendata);
                if(res)
                {
                    sendata.append(",1,TIMER,OK");
                    my_dev_flag=dev_number;
                    my_dev_id=dev_Id;
                    this->myclassdb->info_cabinet_update_heart(dev_Id);
                    this->write(sendata.toLocal8Bit());
                    TIMER_falg=true;
                    if(down_falg)
                    {
                        //this->myclassdb->info_consumer_update_downFlag(1,dev_Id);
                        this->myclassdb->info_consumer_check_downFlag(1,dev_Id);
                        Delete_timer->stop();
                        down_falg=false;
                        Download_timer->start(2000);
                    }else{
                        //this->myclassdb->info_consumer_update_downFlag(2,dev_Id);
                        this->myclassdb->info_consumer_check_downFlag(2,dev_Id);
                        Download_timer->stop();
                        down_falg=true;
                        Delete_timer->start(2000);
                    }
                }else{
                    sendata.append(",1,TIMER,ERROR");
                    this->write(sendata.toLocal8Bit());
                }
            }
            if(dev_flag=="CARD")//客户端发送刷卡请求
            {
                sendata=dev_Id;
                sendata.append(",1,CARD,");
                boxIdInfo Idinfo;
                res=this->myclassdb->box_id_infor(dev_Id,dev_byte,&Idinfo);
                if(res)
                {
                    //qDebug()<<"db->box_id_infor"<<Idinfo.id<<Idinfo.uid;
                    QString box_no=this->myclassdb->box_no_infor(0,Idinfo.id,Idinfo.uid);
                    if(box_no.isEmpty())
                    {
                        sendata.append("NO");
                    }else{
                        sendata.append("OK,").append(box_no);
                        if(box_no.contains("-"))
                        {
                            QStringList list=box_no.split('-');
                            for(int i=0;i<list.count();i++)
                            {
                                //qDebug()<<"myTcpServer::ReadData list.count"<<list.count()<<list[i];
                                this->myclassdb->writeOpenLog(dev_byte,Idinfo.id,list[i],Idinfo.uid);
                            }
                        }else{
                            this->myclassdb->writeOpenLog(dev_byte,Idinfo.id,box_no,Idinfo.uid);
                        }
                    }
                }else{
                    sendata.append("NO");
                }
                if(list.count()==4)
                {
                    this->write(sendata.toLocal8Bit());
                    qDebug()<<"==发送==CARD"<<sendata;
                }
                sendata.clear();
            }
            if(dev_flag=="DOWNLOAD")//下载卡号
            {
                QString card_sn,down_flag;
                bool res;
                down_flag=dev_byte;
                //int card_sum=list[4].toInt();
                // card_sn=QString::number(card_sum);
                card_sn=list[4];
                res=this->myclassdb->box_no_change(down_flag.toInt(),dev_Id,card_sn);
                if(TIMER_falg)
                {
                    return;
                }
                if(down_flag=="1")
                {
                    Download_timer->start(500);
                }
                if(down_flag=="2")
                {
                    Delete_timer->start(500);
                }
            }
            if(dev_flag=="OPEN")//客户端返回开门结果
            {
                OpenDoorData.clear();
                //OpenTime=QDateTime::currentDateTime();
                emit openClientDoorSend(strSend);
                qDebug()<<"myClientSocket::ReadData emit openClientDoorSend"<<dev_number;
            }
        }
        else if(dev_number== "2")//门禁
        {
            if(dev_flag=="TIMER")//客户端发送心跳包(代温度)
            {
                int mTime=OpenTime.secsTo(QDateTime::currentDateTime());
                if(mTime < 3)
                {
                    qDebug()<<"TIMER < 3 "<<mTime;
                    return;
                }
                OpenTime=QDateTime::currentDateTime();
                res=this->myclassdb->mj_controller_sn_infor(dev_Id,&house);
                if(res)
                {
                    this->myclassdb->cfg_controller_update_heart(dev_Id);//心跳包更新
                    bool tes;
                    my_dev_flag=dev_number;
                    my_dev_id=dev_Id;
                    //tes=Download_netdata();
                    tes=this->myclassdb->consumer_info(my_dev_id,MyPersonInfo);
                    if(tes)
                    {
                        Download_timer->start(2000);
                        return;
                    }else
                    {
                        if(!MyPersonInfo->ic_sn.isEmpty())
                        {
                            Download_timer->start(500);
                            return ;
                        }
                        /**********查询同步语音 ************/
                        //this->myclassdb->voiceInfo_down(&this->myclassdb->mySql_db,&this->myclassdb->sqlite_db);//远程同步语音信息
                        //this->myclassdb->voiceInfo_Find(&this->myclassdb->sqlite_db,dev_Id);//本地数据库添加该设备语音信息记录
                        tes=this->myclassdb->info_voice_downFlag(&this->myclassdb->mySql_db,"2",dev_Id,"");//查询本地语音下载
                        /***********************************/
                        if(tes)
                        {
                            Voice_timer->start(3000);
                            //Voice_netdata();
                            return;
                        }
                        sendata=QString("%1,2,TIMER,OK").arg(dev_Id);
                        this->write(sendata.toLocal8Bit());
                        del_num=0;
                        dow_num=0;
                        qDebug()<<"发送="<<sendata;
                    }
                }else{
                    sendata=QString("%1,2,TIMER,ERROR").arg(dev_Id);
                    Download_timer->stop();
                    this->write(sendata.toLocal8Bit());
                    qDebug()<<"发送="<<sendata;
                }
                //mjHouseId(dev_Id);
                //                TIMER_falg=true;
                //                if(down_falg)
                //                {
                //                    //更新房号表中人员为0需要下载的数据
                //                    //this->myclassdb->mj_houseId_Change("1",dev_Id);
                //                    Delete_timer->stop();
                //                    down_falg=false;
                //                    Download_timer->start(2000);
                //                }else{
                //                    //更新人员表中房号为D的数据
                //                    //this->myclassdb->mj_Consumer_Change("2",dev_Id);
                //                    //更新房号表中人员为2需要下载的数据
                //                    //this->myclassdb->mj_houseId_Change("2",dev_Id);
                //                    Download_timer->stop();
                //                    down_falg=true;
                //                    Delete_timer->start(2000);
                //                }
            }
            if(dev_flag=="VOICEMESSAGE")
            {
                QString code,voice_flag;
                voice_flag=list[3];
                code=list[4];
                this->myclassdb->voice_change(&this->myclassdb->sqlite_db,voice_flag,dev_Id,code);
                Voice_timer->start(3000);
                //Voice_netdata();
            }
            if(dev_flag=="DOWNLOAD")
            {
                QString card_sn,down_flag;
                bool res;
                down_flag=dev_byte;
                //int card_sum=list[4].toInt();
                //card_sn=QString::number(card_sum);
                card_sn=list[4];
                res=this->myclassdb->consumer_change(down_flag,dev_Id,card_sn);
                Num_netdata(down_flag,dev_Id);
                if(TIMER_falg)
                {
                    return;
                }
                //Download_netdata();
                Download_timer->start(1000);
                  }
            if(dev_flag=="UPLOAD")
            {
                if(list.count()<7)
                {
                    //qDebug()<<"UPLOAD list.count()<6 return";
                    return;
                }
                Download_timer->stop();
                Delete_timer->stop();
                QString pass_sn,card_no,direction;
                //pass_sn=list[3];
                pass_sn=QDateTime::currentDateTime().toString("yyMMddhhmmsszzz");
                card_no=list[4];
                direction=list[6];
                res=this->myclassdb->record_in_out(pass_sn,dev_Id,card_no,direction);
                if(res)
                {
                    sendata.append(strSend.section(",",0,4)).append(",OK");
                }else{
                    sendata.append(strSend.section(",",0,4)).append(",ERROR");
                }
                this->write(sendata.toLocal8Bit());
                qDebug()<<"==发送==UPLOAD==2:"<<sendata;
            }
            if(dev_flag=="OPEN")
            {
                OpenDoorData.clear();
                //OpenTime=QDateTime::currentDateTime();
                emit openClientDoorSend(strSend);
                //qDebug()<<"myClientSocket::ReadData emit openClientDoorSend"<<dev_number;
            }
            if(dev_flag=="PASSWORD")
            {
                sendata=dev_Id;
                res=this->myclassdb->privilege_infor(dev_Id,dev_byte);
                if(res)
                {
                    sendata.append(tr(",2,PASSWORD,%1,%2,OK").arg(dev_Id).arg(dev_byte));
                }else{
                    sendata.append(tr(",2,PASSWORD,%1,%2,ERROR").arg(dev_Id).arg(dev_byte));
                }
                this->write(sendata.toLocal8Bit());
            }
            if(dev_flag=="UPDATA")
            {
                QString dateStr=DateBack();
                sendata=dev_Id;
                sendata.append(tr(",2,UPDATA,%1").arg(dateStr));
                if(dev_byte=="TIMER")
                {
                    this->write(sendata.toLocal8Bit());
                    qDebug()<<"==发送==UPDATA==2:"<<sendata;
                }
            }
        }
        else if(dev_number== "3")//GPS
        {
            bool res;
            int count = list.count();
            if(count<10)
            {
                //qDebug()<<"dev_number=3 count="<<count;
                return;
            }
            QString vehicle_no,gps_flg,temprature,lati,longi,creatTime;
            vehicle_no=this->myclassdb->vehicle_infor(list[0]);
            temprature=list[3];
            gps_flg=list[6];
            int  gpsLat_1 = static_cast<int>(list[7].toDouble()/100);
            double gpsLat_2 = (list[7].toDouble() - gpsLat_1 * 100)/60;
            double gpslat=gpsLat_1 + gpsLat_2;

            int gpsLong_1 = static_cast<int>(list[9].toDouble()/100);
            double gpsLong_2 = (list[9].toDouble()-gpsLong_1 * 100)/60;
            double gpsLong = gpsLong_1 + gpsLong_2;

            creatTime=list[5];
            lati=QString::number(gpslat,'g',9);
            longi=QString::number(gpsLong,'g',10);
            if(gps_flg=="V")
            {
                lati=QString::number(0);
                longi=QString::number(0);
            }
            //qDebug()<<"GPS"<<count<<temprature<<lati<<longi<<creatTime;
            res=this->myclassdb->writeGpsLog(vehicle_no,temprature,longi,lati);
            sendata=dev_Id;
            // if(res)
            // {
            sendata.append(",3,GPRMC,OK");
            // }else{
            //    sendata.append(",3,GPRMC,ERROR");
            //  }
            this->write(sendata.toLocal8Bit());
        }
    }
}

void myClientSocket::DisConnect()
{ //断开连接时，发送断开信号
    emit ClientDisConnect(this->clientID,this->peerAddress().toString(),this->peerPort());
    //QThread::currentThread()->quit();
}

bool myClientSocket::Download_netdata()//下载
{
    Download_timer->stop();
    TIMER_falg=false;
    bool res;
    if(my_dev_flag==QString::number(1))
    {
        if(this->myclassdb->mySql_db.isOpen())
        {
            res=this->myclassdb->box_sn_infor(1,my_dev_id,&Sninfo);
            if(res)
            {
                QString sendDate;
                sendDate=my_dev_id;
                sendDate.append(",1,DOWNLOAD,1,").append(Sninfo.sn).append(",").append(Sninfo.box);
                this->write(sendDate.toLocal8Bit());
                qDebug()<<"==发送==myClientSocket::Download_netdata"<<sendDate;
                return true;
            }else{    
                if(!Sninfo.sn.isEmpty())
                {
                    this->myclassdb->box_no_change(3,my_dev_id,Sninfo.sn);
                    Download_timer->start(500);
                    //Download_netdata();
                    return true;
                }
                return false;
            }
        }else{
            return false;
        }
    }
    if(my_dev_flag==QString::number(2))
    {
        if(this->myclassdb->mySql_db.isOpen())
        {
            //  this->myclassdb->download_card(my_dev_id);
            res=this->myclassdb->consumer_info(my_dev_id,MyPersonInfo);
            if(res)
            {
                //qDebug()<<"myClient_card_no"<<myClient_card_no<<"MyPersonInfo->ic_sn"<<MyPersonInfo->ic_sn;
                myClient_card_no=MyPersonInfo->ic_sn;
                QString MySendData=my_dev_id;
                if(MyPersonInfo->down_flag=="N")
                {
                    MySendData.append(QString(",2,DOWNLOAD,1,%1,%2,%3").arg(MyPersonInfo->ic_sn).arg(MyPersonInfo->end_ate).arg(MyPersonInfo->voice_id));
                }else{
                    MySendData.append(QString(",2,DOWNLOAD,2,%1,%2,%3").arg(MyPersonInfo->ic_sn).arg(MyPersonInfo->end_ate).arg(MyPersonInfo->voice_id));
                }
                this->write(MySendData.trimmed().toLocal8Bit());
                qDebug()<<"==发送==myClientSocket::Download_netdata"<<MySendData;
                return true;
            }else{
                if(!MyPersonInfo->ic_sn.isEmpty())
                {
                    //this->myclassdb->house_change("1",my_dev_id,MyPersonInfo->house);
                    //this->myclassdb->consumer_change("3",my_dev_id,MyPersonInfo->id);
                    if(MyPersonInfo->down_flag=="N")
                    {
                        this->myclassdb->consumer_change("3",my_dev_id,MyPersonInfo->id);
                    }else{
                        this->myclassdb->consumer_change("4",my_dev_id,MyPersonInfo->id);
                    }
                    Download_timer->start(500);
                    //Download_netdata();
                    return true;
                }
                return false;
            }
        }else{
            return false;
        }
    }
}

void myClientSocket::Delete_netdata()//下载
{
    Delete_timer->stop();
    TIMER_falg=false;
    bool res;
    if(my_dev_flag==QString::number(1))
    {
        if(this->myclassdb->mySql_db.isOpen())
        {
            res=this->myclassdb->box_sn_infor(2,my_dev_id,&Sninfo);
            if(res)
            {
                QString sendDate;
                sendDate=my_dev_id;
                //sendDate.append(",1,DOWNLOAD,2,").append(Sninfo.sn).append(",").append(Sninfo.box);
                sendDate.append(",1,DOWNLOAD,2,").append(Sninfo.sn);
                this->write(sendDate.toLocal8Bit());
                qDebug()<<"==发送==myClientSocket::Delete_netdata"<<sendDate;
            }else{
                if(!Sninfo.sn.isEmpty())
                {
                    this->myclassdb->box_no_change(4,my_dev_id,Sninfo.sn);
                    Delete_timer->start(500);
                }
            }
        }
    }
    if(my_dev_flag==QString::number(2))//门禁
    {
        if(this->myclassdb->mySql_db.isOpen())
        {
            //this->myclassdb->download_card(my_dev_id);
            res=this->myclassdb->consumer_info(my_dev_id,MyPersonInfo);
            if(res)
            {
                myDelet_card_no=MyPersonInfo->ic_sn;
                QString MyDeleteData=my_dev_id;
                //MyDeleteData.append(",2,DOWNLOAD,2,").append(MyPersonInfo->ic_sn).append(",").append(MyPersonInfo->end_ate);
                if(MyPersonInfo->down_flag=="N")
                {
                    MyDeleteData.append(QString(",2,DOWNLOAD,1,%1,%2,%3").arg(MyPersonInfo->ic_sn).arg(MyPersonInfo->end_ate).arg(MyPersonInfo->voice_id));
                }else{
                    MyDeleteData.append(QString(",2,DOWNLOAD,2,%1,%2,%3").arg(MyPersonInfo->ic_sn).arg(MyPersonInfo->end_ate).arg(MyPersonInfo->voice_id));
                }
                this->write(MyDeleteData.toLocal8Bit());
                qDebug()<<"==发送==myClientSocket::Delete_netdata"<<MyDeleteData;
            } else{
                if(!MyPersonInfo->ic_sn.isEmpty())
                {
                    if(MyPersonInfo->down_flag=="N")
                    {
                        this->myclassdb->consumer_change("3",my_dev_id,MyPersonInfo->id);
                    }else{
                        this->myclassdb->consumer_change("4",my_dev_id,MyPersonInfo->id);
                    }
                    Delete_timer->start(500);
                }
            }
        }
    }
}

void myClientSocket::Voice_netdata()//语音
{
    Voice_timer->stop();
    if(my_dev_flag==QString::number(2))
    {
        if(this->myclassdb->mySql_db.isOpen())
        {
            //this->myclassdb->download_card(my_dev_id);
            voiceInfo InfoVoice;
            bool res;
            res=this->myclassdb->voice_infor(&this->myclassdb->mySql_db,my_dev_id,&InfoVoice);
            if(res)
            {
                QString MyDeleteData=my_dev_id;
                if(InfoVoice.open_flag=="N")
                {
                    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));
                    MyDeleteData.append(QString(",2,VOICEMESSAGE,1,%1,%2").arg(InfoVoice.code).arg(InfoVoice.voice));
                    this->write(MyDeleteData.toLocal8Bit());
                    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
                    qDebug()<<"==发送==myClientSocket::Voice_netdata"<<MyDeleteData;
                }else if(InfoVoice.open_flag=="D")
                {
                    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));
                    MyDeleteData.append(QString(",2,VOICEMESSAGE,2,%1,%2").arg(InfoVoice.code).arg(InfoVoice.voice));
                    this->write(MyDeleteData.toLocal8Bit());
                    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
                    qDebug()<<"==发送==myClientSocket::Voice_netdata"<<MyDeleteData;
                }
            }else{
                if(!InfoVoice.id.isEmpty())
                {
                    this->myclassdb->voice_change(&this->myclassdb->sqlite_db,"3",my_dev_id,InfoVoice.id);
                    Voice_timer->start(500);
                    //  Voice_netdata();
                }
            }
        }
    }
}

QString  myClientSocket::DateBack()
{
    QString str;
    QString Cudate=QDate::currentDate().toString("ddd");
    str=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ");
    if(Cudate=="周一")
    {
        str.append("1");
    }
    if(Cudate=="周二")
    {
        str.append("2");
    }
    if(Cudate=="周三")
    {
        str.append("3");
    }
    if(Cudate=="周四")
    {
        str.append("4");
    }
    if(Cudate=="周五")
    {
        str.append("5");
    }
    if(Cudate=="周六")
    {
        str.append("6");
    }
    if(Cudate=="周日")
    {
        str.append("7");
    }
    return str;
}

void myClientSocket::OpenDoorSlot(QString data)
{
    Download_timer->stop();
    Delete_timer->stop();
    //    if(data==OpenDoorData)
    //    {
    //        Send_timer->start(5000);
    //        return;
    //    }
    OpenDoorData=data;
    this->write(OpenDoorData.toLocal8Bit());
    qDebug()<<"=发送="<<this->clientID<<OpenDoorData;
}

void myClientSocket::Send_netdata()
{
    Send_timer->stop();
    qDebug()<<"Send_netdata"<<OpenDoorData;
    this->write(OpenDoorData.toLocal8Bit());
}

void myClientSocket::Num_netdata(QString  flag,QString dev)
{
    if(flag=="1")
    {
     dow_num++;
     qDebug()<<QString("%1下载数目%2").arg(dev).arg(dow_num);
    }else{
      del_num++;
      qDebug()<<QString("%1删除数目%2").arg(dev).arg(del_num);
    }
}
